import React from 'react';
import { WebView, Animated, ActivityIndicator, Image, Keyboard, ScrollView, StyleSheet, Text, View, TouchableOpacity, Modal, TextInput, TouchableWithoutFeedback, DeviceEventEmitter, FlatList } from 'react-native';

import ImagePicker from 'react-native-image-picker'
import RadioModal from '../Component/RadioModal'

import ScreenUtils from '../Utils/ScreenUtils'
import ColorUtils from '../Utils/ColorUtils'
import RouterUtils from '../Utils/RouterUtils'
import ToastUtils from '../Utils/ToastUtils'
import StorageUtils from '../Utils/StorageUtils'
import Constant from '../Constant/Constant'
import HttpUtils from '../Utils/HttpUtils'
import RuleUtils from '../Utils/RuleUtils'
import TimeUtils from '../Utils/TimeUtils'

const options = {
    title: '请选择',
    cancelButtonTitle: '取消',
    takePhotoButtonTitle: '拍照',
    chooseFromLibraryButtonTitle: '选择相册',
    quality: 0.75,
    allowsEditing: false,
    noData: false,
    storageOptions: {
        skipBackup: true,
        path: 'images',
    },
}

export default class PageLwpcSubAdd extends React.Component
{
    static navigationOptions = ({navigation}) => ({
        gesturesEnabled: false,//是否支持滑动返回收拾，iOS默认支持，安卓默认关闭
        headerTitle: '房屋信息',
        headerStyle: {
            backgroundColor: ColorUtils.blue,
            height: ScreenUtils.statusBarHeight,
        },
        headerRight: (<Text></Text>),
        headerTintColor: ColorUtils.white,
        headerTitleStyle: {
            fontSize: ScreenUtils.Font_18,
            color: ColorUtils.white,
            fontWeight: 'normal',
            flex: 1,
            alignSelf: 'center',
            textAlign: 'center',
        }
    });

    constructor(props)
    {
        super(props);
        this.state = {
            uploadPics: [],
            hasCertificate: '',
            houseType: '',
            houseAmount: '',
            houseArea: '',
            certificateNumber: '',
            geoLocation: '',
            geoAddress: '请选择采集地点',
        };
    }

    componentDidMount()
    {
        RouterUtils.pushRouter('PageLwpcSubAdd', this.props.navigation.state.key);
        this.listener1 = DeviceEventEmitter.addListener('postLocation', (events) => this.postLocation(events));
    }

    componentWillUnmount()
    {
        RouterUtils.popRouter('PageLwpcSubAdd', this.props.navigation.state.key);
        this.listener1.remove();
    }

    casePublishClick()
    {
        try
        {
            // RuleUtils.checkEmpty(this.state.address, '地址不能为空')
            // RuleUtils.checkUnSelect(this.state.buildState, '请先选择');
            // RuleUtils.checkUnSelect(this.state.structureType, '请先选择');
            // RuleUtils.checkUnSelect(this.state.structureMethod, '请先选择');
            // RuleUtils.checkUnSelect(this.state.landStatus, '请先选择');
            var that = this;
            var data = {
                "houseCollectionId": this.props.navigation.state.params.item.id,
                "hasCertificate": this.state.hasCertificate,
                "houseType": this.state.houseType,
                "houseAmount": this.state.houseAmount,
                "houseArea": this.state.houseArea,
                "certificateNumber": this.state.certificateNumber,
                "geo": this.state.geoLocation,
                "houseAddress": this.state.geoAddress,
                "housePicture": this.toStringPicsUrl()
            };
            console.log(JSON.stringify(data))
            StorageUtils.get('session').then((session) =>
            {
                if (session != '' && session != null)
                {
                    HttpUtils.postJsonWithRaw(Constant.lwpcReportSubAdd, session, JSON.stringify(data), function (resultcode, data)
                    {
                        ToastUtils.toastShortBottom('采集信息上报成功')
                        DeviceEventEmitter.emit('getLwpcSubList', 'param');
                        that.props.navigation.goBack();
                    }, function (resultcode, reason)
                    {
                        ToastUtils.toastShortBottom('错误码:' + resultcode + ',错误原因:' + reason);
                    });
                }
            });
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    postLocation(event)
    {
        console.log(event)
        var data = JSON.parse(event);
        this.setState({
            geoAddress: data.address,
            geoLocation: data.geolocation.lng + ',' + data.geolocation.lat,
        })
    }

    jumpLocation()
    {
        this.props.navigation.navigate('WebPage', {'title': '当前位置', 'url': Constant.mapServer + '?type=dingwei'})
    }

    jumpPhoto()
    {
        if (this.state.uploadPics.length >= 1)
        {
            ToastUtils.toastShortCenter('最多上传一张照片')
            return;
        }
        ImagePicker.showImagePicker(options, (response) =>
        {
            if (response.didCancel)
            {
                console.log('User cancelled image picker');
            } else if (response.error)
            {
                console.log('ImagePicker Error: ', response.error);
            } else if (response.customButton)
            {
                console.log('User tapped custom button: ', response.customButton);
            } else
            {
                var that = this;
                HttpUtils.uploadPic(Constant.uploadReportImg, response.uri, function (resultcode, data)
                {
                    ToastUtils.toastShortBottom('上传图片成功');
                    var imgUrl = {url: data.link.toString()};
                    that.state.uploadPics.push(imgUrl);
                    that.setState({
                        uploadPics: that.state.uploadPics
                    })
                }, function (resultcode, reason)
                {
                    ToastUtils.toastShortBottom('错误码:' + resultcode + ',错误原因:' + reason);
                });
            }
        });
    }

    toStringPicsUrl()
    {
        var pics = '';
        for (var i = 0; i < this.state.uploadPics.length; i++)
        {
            pics = pics + this.state.uploadPics[i].url + ',';
        }
        pics = pics.substr(0, pics.lastIndexOf(','))
        return pics;
    }

    renderUploadPics()
    {
        let allData = [];
        for (let i = 0; i < this.state.uploadPics.length; i++)
        {
            let item = this.state.uploadPics[i];
            allData.push(
                <TouchableWithoutFeedback key={item.url} onLongPress={() =>
                {
                    this.showLongPressDelPicModal(item, 'pics')
                }}>
                    <Image style={{width: 80, height: 80, borderColor: ColorUtils.line, borderWidth: 1, borderRadius: 10, marginRight: 8,}} source={{uri: item.url}}/>
                </TouchableWithoutFeedback>
            );
        }
        allData.push(
            <TouchableOpacity activeOpacity={0.8} onPress={() => this.jumpPhoto()} key={-1} style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center', borderStyle: 'dashed', borderColor: ColorUtils.line, borderWidth: 1, borderRadius: 10, width: 80, height: 80}}>
                <Image style={{width: 16, height: 16}} source={require('../img/img_add.png')}/>
            </TouchableOpacity>
        );
        return allData;
    }

    render()
    {
        return (
            <View style={styles.container}>
                <View activeOpacity={0.8} style={{flexDirection: 'row', alignItems: 'center', height: 58, paddingTop: 8, paddingBottom: 8, paddingLeft: 16, paddingRight: 16, borderBottomWidth: 1, borderBottomColor: ColorUtils.line}}>
                    <Text style={{flex: 1, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>房屋类型</Text>
                    <TextInput value={this.state.houseType} underlineColorAndroid='transparent' keyboardType='default' maxLength={20} placeholder='请输入' onChangeText={(text) => this.setState({houseType: text})} multiline={true}
                               style={{color: ColorUtils.gray, fontSize: ScreenUtils.Font_14, width: 200, textAlign: 'right', marginRight: 8}}/>
                </View>
                <View activeOpacity={0.8} style={{flexDirection: 'row', alignItems: 'center', height: 58, paddingTop: 8, paddingBottom: 8, paddingLeft: 16, paddingRight: 16, borderBottomWidth: 1, borderBottomColor: ColorUtils.line}}>
                    <Text style={{flex: 1, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>房屋数量</Text>
                    <TextInput value={this.state.houseAmount} underlineColorAndroid='transparent' keyboardType='numeric' maxLength={20} placeholder='请输入' onChangeText={(text) => this.setState({houseAmount: text})} multiline={true}
                               style={{color: ColorUtils.gray, fontSize: ScreenUtils.Font_14, width: 200, textAlign: 'right', marginRight: 8}}/>
                </View>
                <View activeOpacity={0.8} style={{flexDirection: 'row', alignItems: 'center', height: 58, paddingTop: 8, paddingBottom: 8, paddingLeft: 16, paddingRight: 16, borderBottomWidth: 1, borderBottomColor: ColorUtils.line}}>
                    <Text style={{flex: 1, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>房屋面积(㎡)</Text>
                    <TextInput value={this.state.houseArea} underlineColorAndroid='transparent' keyboardType='numeric' maxLength={20} placeholder='请输入' onChangeText={(text) => this.setState({houseArea: text})} multiline={true}
                               style={{color: ColorUtils.gray, fontSize: ScreenUtils.Font_14, width: 200, textAlign: 'right', marginRight: 8}}/>
                </View>
                <TouchableOpacity activeOpacity={0.8} style={{flexDirection: 'row', alignItems: 'center', height: 58, paddingTop: 8, paddingBottom: 8, paddingLeft: 16, paddingRight: 16, borderBottomWidth: 1, borderBottomColor: ColorUtils.line}}>
                    <Text style={{flex: 1, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>是否有证书</Text>
                    <RadioModal
                        ref="RadioModal7"
                        innerStyle={{width: 50,}}
                        noneColor={'#efefef'}
                        selectedValue="0"
                        onValueChange={(id) => this.setState({hasCertificate: id})}
                        style={{flexDirection: 'row', justifyContent: 'center'}}>
                        <Text style={{color: ColorUtils.light_gray, fontSize: ScreenUtils.Font_14}} value="0">无</Text>
                        <Text style={{color: ColorUtils.light_gray, fontSize: ScreenUtils.Font_14}} value="1">有</Text>
                    </RadioModal>
                </TouchableOpacity>
                <View activeOpacity={0.8} style={{display: this.state.hasCertificate == '1' ? 'flex' : 'none', flexDirection: 'row', alignItems: 'center', height: 58, paddingTop: 8, paddingBottom: 8, paddingLeft: 16, paddingRight: 16, borderBottomWidth: 1, borderBottomColor: ColorUtils.line}}>
                    <Text style={{flex: 1, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>证书编号</Text>
                    <TextInput value={this.state.certificateNumber} underlineColorAndroid='transparent' keyboardType='default' maxLength={20} placeholder='请输入' onChangeText={(text) => this.setState({certificateNumber: text})} multiline={true}
                               style={{color: ColorUtils.gray, fontSize: ScreenUtils.Font_14, width: 200, textAlign: 'right', marginRight: 8}}/>
                </View>
                <TouchableOpacity activeOpacity={0.8} onPress={() => this.jumpLocation()} style={{flexDirection: 'row', alignItems: 'center', height: 58, paddingTop: 8, paddingBottom: 8, paddingLeft: 16, paddingRight: 16, borderBottomWidth: 1, borderBottomColor: ColorUtils.line}}>
                    <Text style={{flex: 1, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>采集位置</Text>
                    <Text numberOfLines={2} style={{textAlign: 'right', width: 220, marginRight: 16, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{this.state.geoAddress}</Text>
                    <View style={{width: 14, justifyContent: 'center', alignItems: 'center'}}>
                        <Image style={{width: 14, height: 18}} source={require('../img/map_location.png')}/>
                    </View>
                </TouchableOpacity>
                <View style={{flexDirection: 'row', height: 120, paddingTop: 8, paddingBottom: 8, paddingLeft: 16, paddingRight: 16, borderBottomWidth: 1, borderBottomColor: ColorUtils.line}}>
                    <View style={{width: 80, height: 50, flexDirection: 'row', alignItems: 'center',}}>
                        <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>房屋照片</Text>
                    </View>
                    <ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
                        <View style={{width: ScreenUtils.width - 112, flex: 1, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center',}}>
                            {this.renderUploadPics()}
                        </View>
                    </ScrollView>
                </View>
                <View style={{flexDirection: 'row', alignItems: 'center', marginLeft: 16, marginRight: 16, marginTop: 16, marginBottom: 100}}>
                    <TouchableOpacity activeOpacity={0.8} onPress={() => this.casePublishClick()} style={{marginLeft: 16, flex: 1, justifyContent: 'center', alignItems: 'center', height: 44, borderRadius: 6, backgroundColor: ColorUtils.blue}}>
                        <Text style={{color: ColorUtils.white, fontSize: ScreenUtils.Font_14}}>
                            上报数据
                        </Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: ColorUtils.white,
    },
});


